using System.Collections.Generic;
using System.Linq;

namespace Beaker.Services.FileSystem
{
	public static class FileSystemServiceExtensions
	{
		public static IFile GetFile( this IFolder folder, string firstName, params string[] moreNames )
		{
			if( folder == null || firstName == null )
				return null;

			string[] names = new[] { firstName }.Concat( moreNames ?? new string[0] ).ToArray();
			for( int i = 0; i < names.Length; i++ )
			{
				if( folder == null )
					return null;

				if( i < names.Length - 1 )
					folder = folder.GetFolder( names[i] );
				else
					return folder.GetFile( names[i] );
			}

			return null;
		}

		public static IFolder GetFolder( this IFolder folder, string firstName, params string[] moreNames )
		{
			if( folder == null || firstName == null )
				return null;

			string[] names = new[] { firstName }.Concat( moreNames ?? new string[0] ).ToArray();
			foreach( string name in names )
			{
				if( folder == null )
					return null;

				folder = folder.GetFolder( name );
			}

			return folder;
		}

		public static string GetFileNameWithoutExtension( this IFile file )
		{
			if( file == null )
				return null;

			var i = file.Name.LastIndexOf( '.' );
			if( i == -1 )
				return file.Name;

			return file.Name.Substring( 0, i );
		}

		/// <summary>
		/// Gets all files from this and all possible nested folders
		/// </summary>
		/// <param name="folder">The folder to get all files from, recursivly scanning sub-folders aswell.</param>
		/// <returns>A sequence of all the files.</returns>
		public static IEnumerable<IFile> GetAllFilesRecursive( this IFolder folder )
		{
			foreach( IFile file in folder.GetFiles() )
				yield return file;

			foreach( IFolder subFolder in folder.GetFolders() )
				foreach( IFile subFile in subFolder.GetAllFilesRecursive() )
					yield return subFile;
		}
	}
}